package com.xdap.keymen.service.punch;

import com.definesys.mpaas.query.MpaasQuery;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.xdap.keymen.entity.*;
import com.xdap.motor.vo.ResponseVo;
import com.xdap.runtime.service.RuntimeAppContextService;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.h2.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 客诉单
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class PunchCustomerComplaintService extends PunchBaseService {
    private final RuntimeDatasourceService runtimeDatasourceService;
    private final RuntimeAppContextService runtimeAppContextService;
    private final PunchSalesSupportTicketService punchSalesSupportTicketService;

    private final PunchXdapAttachmentsService punchXdapAttachmentsService;
    public ResponseVo saveCustomerComplaint(String YXCNum){
        try {
            SimpleDateFormat formatDate =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Map<String, Object> params = new HashMap<>();
            Gson gson = new GsonBuilder().create();
            List<PunchCustomerComplaintItemRequestEntity> list = new ArrayList<>();
            PunchCustomerComplaintEntity entity = getCustomerComplaint(YXCNum);
            if (entity == null) {
                return ResponseVo.error("客诉单没找到");
            }
            //工单编号
            String strSupportTicketNumber = "";
            if (!StringUtils.isNullOrEmpty(entity.getSupportTicketNumber())) {
                PunchSalesSupportTicketEntity ticketEntity = punchSalesSupportTicketService.getSalesSupportTicket(entity.getSupportTicketNumber().replace("[\"", "").replace("\"]", ""));
                if (ticketEntity != null) {
                    strSupportTicketNumber = ticketEntity.getSupportTicketNumber();
                }
            }
            //意见分类
            String getOpinionType = "";
            String optionType = "";
            if (!StringUtils.isNullOrEmpty(entity.getOpinionType())) {
                optionType = entity.getOpinionType();
            }
            getOpinionType = (optionType.contains("1") ? "1" : "0")
                    .concat(optionType.contains("2") ? "1" : "0")
                    .concat(optionType.contains("3") ? "1" : "0")
                    .concat(optionType.contains("4") ? "1" : "0")
                    .concat(optionType.contains("5") ? "1" : "0");

            PunchCustomerComplaintRequestEntity requestEntity = new PunchCustomerComplaintRequestEntity();
            //BeanUtils.copyProperties(entity,requestEntity);
            requestEntity.setCc_form_number(entity.getCcFormNumber());
            //这两个字段去掉
            //requestEntity.setUsage_quantity(entity.getUsageQuantity());
            //requestEntity.setDefective_quantity(entity.getDefectiveQuantity());
            requestEntity.setProblem_description(entity.getProblemDescription());
            requestEntity.setNeed_report(entity.getNeedReport());
            requestEntity.setBuzuo_fanxiu(entity.getBuzuoFanxiu());
            requestEntity.setProduct_return(entity.getProductReturn());
            requestEntity.setOpinion_type(getOpinionType);
            requestEntity.setBusiness_office_oppion(entity.getBusinessOfficeOppion());
            requestEntity.setComplaintTime(formatDate.format(entity.getCreationDate()));
            //String salesBackOffice=entity.getSalesBackOffice()==null?"":entity.getSalesBackOffice();
            requestEntity.setSalesBackOffice(entity.getSalesBackOffice()==null?"":entity.getSalesBackOffice());
            //requestEntity.setSupportTicketNumber(entity.getSupportTicketNumber());
            requestEntity.setSupportTicketNumber(strSupportTicketNumber);
            requestEntity.setKehuyaoqiu(entity.getKehuyaoqiu());
            requestEntity.setSales_order_number(entity.getSalesOrderNumber());
            //处理附件
            String attachmentOrImages = "";
            String[] arrayAtta = gson.fromJson(entity.getReport(), String[].class);
            if (arrayAtta != null) {
                for (String atta : arrayAtta) {
                    if (!StringUtils.isNullOrEmpty(atta)) {
                        //arrayList.add(punchXdapAttachmentsService.getXdapAttachmentsUrl(atta));
                        String url = punchXdapAttachmentsService.getXdapAttachmentsUrl(atta);
                        attachmentOrImages = attachmentOrImages + url + ",";
                    }
                }
            }

            requestEntity.setAttachment_or_images(attachmentOrImages);
            params.put("objCustFormMain", requestEntity);

            //处理明细
            PunchCustomerComplaintItemRequestEntity itemRequestEntity;
            List<PunchCustomerComplaintItemEntity> listItemEntity = getCustomerComplaintItem(entity.getDocumentId());
            for (PunchCustomerComplaintItemEntity itemEntity : listItemEntity) {
                itemRequestEntity = new PunchCustomerComplaintItemRequestEntity();
                itemRequestEntity.setCc_form_number(YXCNum);
                itemRequestEntity.setCc_form_line_number(itemEntity.getYxcLine());
                itemRequestEntity.setSales_order_number(itemEntity.getSalesOrderNumber());
                itemRequestEntity.setSales_order_line_number(itemEntity.getSalesOrderLineNumber());
                itemRequestEntity.setMaterial_code(itemEntity.getMaterialCode()==null?"":itemEntity.getMaterialCode());
                itemRequestEntity.setMaterial_description(itemEntity.getMaterialDescription());
                itemRequestEntity.setOrder_quantity(itemEntity.getOrderQuantity());
                itemRequestEntity.setQty_kesu_n(itemEntity.getQtyKesuN());
                itemRequestEntity.setQty_used_n(itemEntity.getQtyUsedN());


                list.add(itemRequestEntity);
            }
            params.put("lstCustFormZi", list);


            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "Bearer " + getPunchToken());
            String strJson = gson.toJson(params);
            log.info("客诉单json={}", strJson);
            String response = "";
            response = okHttpUtils.doPostJson(punchConfig.getUrl().concat("/CRM/api/custclaim/save"), strJson, headers, new HashMap<>());
            JsonObject jsonObject = gson.fromJson(response, JsonObject.class);
            if (jsonObject.get("Result").getAsString().equals("True")) {
                return ResponseVo.ok();
            } else {
                String rtn = jsonObject.get("Result").getAsString();
                if (StringUtils.isNullOrEmpty(rtn)) {
                    rtn = jsonObject.get("Errors").getAsString();
                }
                return ResponseVo.error(rtn);
            }
        }catch (Exception e){
            return ResponseVo.error(e.getMessage());
        }
    }

    private PunchCustomerComplaintEntity getCustomerComplaint(String YXCNum) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.eq("cc_form_number", YXCNum);
        return query.doQueryFirst(PunchCustomerComplaintEntity.class);
    }

    public List<PunchCustomerComplaintItemEntity> getCustomerComplaintItem(String tabDocId) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.eq("tab_doc_id",tabDocId);
        return query.doQuery(PunchCustomerComplaintItemEntity.class);
    }
}
